package com.example.taluo.logic;

import com.example.taluo.entity.dto.gamedto.Card;
import com.example.taluo.entity.dto.gamedto.GameState;
import com.example.taluo.entity.dto.gamedto.PlayerState;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/2/18 16:58

 * @Version 1.0*/
public class GameLogic {
    private final CardManager cardManager;
    private final VictoryConditionChecker victoryChecker;

    public GameLogic() {
        this.cardManager = new CardManager();
        this.victoryChecker = new VictoryConditionChecker();
    }
    public void initializeGame(GameState gameState) {
        gameState.getPlayers().values().forEach(player -> {
            player.setDeck(cardManager.initializeDeck());
            System.out.println("Initialized deck for player: " + player.getId() + ", Deck size: " + player.getDeck().size());
            cardManager.drawCards(player, 3);
            System.out.println("Player " + player.getId() + " drew " + player.getHand().size() + " cards.");
        });

        List<String> playerIds = new ArrayList<>(gameState.getPlayers().keySet());
        if (!playerIds.isEmpty()) {
            int randomIndex = new Random().nextInt(playerIds.size());
            String startingPlayerId = playerIds.get(randomIndex);
            gameState.setCurrentPlayerId(startingPlayerId);
            System.out.println("Starting player: " + startingPlayerId);
        }
    }

    public void switchTurn(GameState gameState) {
        // 获取当前玩家ID
        String currentPlayerId = gameState.getCurrentPlayerId();
        // 获取所有玩家ID
        List<String> playerIds = new ArrayList<>(gameState.getPlayers().keySet());

        // 找到当前玩家的索引
        int currentIndex = playerIds.indexOf(currentPlayerId);
        if (currentIndex == -1) {
            // 如果当前玩家ID不在列表中，可能是游戏状态错误
            throw new IllegalStateException("Current player ID not found in player list.");
        }

        // 切换到下一个玩家
        int nextIndex = (currentIndex + 1) % playerIds.size();
        String nextPlayerId = playerIds.get(nextIndex);

        // 更新当前玩家ID
        gameState.setCurrentPlayerId(nextPlayerId);
    }

    public void useCard(GameState gameState, int cardId) {
        PlayerState currentPlayer = gameState.getPlayer(gameState.getCurrentPlayerId());
        PlayerState opponent = getOpponent(gameState, String.valueOf(currentPlayer.getId()));

        if (currentPlayer != null && opponent != null) {
            Card card = currentPlayer.getHand().stream()
                    .filter(c -> c.getId() == cardId)
                    .findAny()
                    .orElse(null);

            if (card != null) {
                currentPlayer.getHand().remove(card);
                cardManager.applyCardEffects(card, currentPlayer, opponent);

                // 检查胜利条件
                if (victoryChecker.checkVictory(currentPlayer, opponent)) {
                    gameState.setGameEnded(true);
                    gameState.setWinnerId(String.valueOf(currentPlayer.getId()));
                } else {
                    // 如果没有结束游戏，切换回合
                    switchTurn(gameState);
                }
            }
        }
    }

    private PlayerState getOpponent(GameState gameState, String currentPlayerId) {
        Set<String> playerIds = gameState.getPlayers().keySet();
        PlayerState opponent = null;
        for (String playerId : playerIds) {
            if (!playerId.equals(currentPlayerId)) {
                opponent = gameState.getPlayer(playerId);
                break;
            }
        }
        return opponent;
    }
}